<template>
    <div class="lz-opticalbox">
        <el-row :gutter="8" v-if="type==2">
            <el-col :span="6">
                <el-date-picker type="daterange" placeholder="选择日期" v-model="expireTime" value-format="yyyy-MM-dd" style="width: 100%;" />
            </el-col>
            <el-col :span="4">
                <el-select v-model="queryOpenType" style="width:100%" placeholder="开锁方式">
                    <el-option v-for="item in typeArray" :key="item.index" :label="item.label" :value="item.index"></el-option>
                </el-select>
            </el-col>
            <el-col :span="2">
                <el-button size="mini" type="primary" @click="currentChange(1)">搜索</el-button>
            </el-col>
        </el-row>
         <el-row :gutter="8" v-else-if="type==1">
             <el-col :span="4">
                <el-input placeholder="昵称" v-model.trim="nickName"></el-input>
             </el-col>
            <el-button size="mini" type="primary" @click="currentChange(1)">搜索</el-button>
            <el-button @click="handleFace(1)">新增人脸</el-button>
        </el-row>
        <el-table :data="tableData" class="record_list" max-height="400px">
            <el-table-column property="avatar" label="头像" width="120">
                <template #default="{row}">
                    <div style="width:80px; height:80px; overflow:hidden; border-radius: 50%">
                        <img :src="row.avatar" alt="" width="100%">
                    </div>
                    <!-- <el-avatar :src="row.avatar" :size="80"></el-avatar> -->
                </template>
            </el-table-column>
            <el-table-column property="nickName" label="名称" width="240"></el-table-column>
            <el-table-column property="name" label="卡/密码" width="150" v-if="type==3"></el-table-column>
            <el-table-column property="phone" label="开锁方式" width="100" v-if="type==2">
                <template #default="{row}">{{lockTypeText(row.type)}}</template>
            </el-table-column>
            <el-table-column property="createTime" label="开锁时间" width="150" v-if="type!=1"></el-table-column>
            <el-table-column property="startTime" label="开始时间" width="150" v-if="type!=2"></el-table-column>
            <el-table-column property="endTime" label="结束时间" width="150" v-if="type!=2"></el-table-column>
            <el-table-column property="lockType" label="开锁说明" v-if="type!=1">
                <!-- <template slot-scope="scope">
                    <span>{{ getLockExplain(scope.row.lockType) }}</span>
                </template> -->
            </el-table-column>
            <el-table-column property="status" label="状态">
                <template slot-scope="{row}">
                    <span class="lockStatus" v-if="type==1" >{{getStatusText(row.status)}}</span>
                    <span class="lockStatus" v-else-if="type==2">{{getStatusText(row.succ)}}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" v-if="type!=2">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleFace(2, scope.row)">延时</el-button>
                    <el-popconfirm title="确定删除吗？" @confirm="handleFace(3, scope.row)">
                        <el-button slot="reference" size="mini">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination class="pagination pt-2 pb-2 justify-content-end" background layout="prev, pager, next"
            :total="totalElements" :page-size.sync="pageSize" @current-change="currentChange"></el-pagination>
        
        
        <AvatarCut v-if="faceDialogVisible" :config="editFaceRow"
             @close="faceDialogVisible = $event"
             @success="faceImgChange"/>
            

        <el-dialog append-to-body width="450px" :visible.sync="lazyDialogVisible"
            @close="lazyDialogVisible=false" 
            v-if="lazyDialogVisible">
            <el-form>
                <el-form-item label="开始时间">
                    <el-input v-model="editFaceRow.startTime" disabled></el-input>
                </el-form-item>
                <el-form-item label="结束时间">
                    <el-date-picker style="width:100%" :picker-options="pickerOption1"
                        v-model="endTime" type="datetime" placeholder="选择结束时间"
                        value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="lazyDialogVisible=false">取消</el-button>
                <el-button @click="changeLazyTime">确定</el-button>
            </template>
        </el-dialog>

    </div>
</template>

<script>
import newService from '@/service/other.service.js';
import { mapState } from 'vuex';
import AvatarCut from '@/components/AvatarCut.vue';
import moment from 'moment';

export default {
    name: 'OpticalBoxDetail',
    components: {
        AvatarCut
    },
    computed: {
        ...mapState({
            userInfo: 'userInfo'
        }),
        typeArray() {
            return ['所有', '远程开锁', '超级密码', '机械开锁', '离线密码', '离线卡', '限时指纹', '限时密码', '限时感应', '限时人脸', '蓝牙开锁'].map((v, i)=>{
                return {
                    index: i,
                    label: v
                }
            });
        }
    },
    props: {
        data: Object,
        type: Number
    },
    data(){
        return {
            pageIndex: 1,
            pageSize: 20,
            totalElements: 0,
            expireTime: null,
            queryOpenType: 0,

            tableData: [],

            faceDialogVisible: false,
            nickName:'',
            editFaceRow: null,

            lazyDialogVisible:  false,
            endTime: '',
            pickerOption1: {
                disabledDate: time => {
                    var start = moment(this.editFaceRow.startTime);
                    var argTime = moment(time);
                    return argTime.isBefore(start);
                }
            }
        }
    },
    created(){
        if( this.type == 1 ) this.fetchFaceList();
        else if( this.type == 2 ) this.fetchLog();
        else this.fetchRecordList();
    },
    methods: {
        handleFace(type, row) {
            this.editFaceRow = row || {};
            if( type == 2 ) {
                this.endTime = row.endTime;
                this.lazyDialogVisible = true;
                return ;
            }
            if( type == 3 ) {
                var url = newService.Api.delFaces + '/' + this.data.lockId + '/' + row.pitNum;
                newService.httpGet(url, {}, {bussinessNo: this.userInfo.userNo}).then(resp=>{
                    if( resp.code===1000 ) {
                        this.$message.success('操作成功！');
                        this.currentChange(1);
                    }
                });
            }
            if( type == 1 ) this.faceDialogVisible = true;
        },
        changeLazyTime() {
            if( !this.endTime ) return this.$message.warning('请选择结束时间');
            var url = newService.Api.updateFaceTime + '/' + this.data.lockId;
            var params = {
                pitNum: this.editFaceRow.pitNum,
                startTime: this.editFaceRow.startTime,
                endTime: this.endTime
            };
            url += '?' + Object.keys(params).map(key=>`${key}=${params[key]}`).join('&');
            newService.httpPost(url, {}, {bussinessNo: this.userInfo.userNo}).then(resp=>{
                if( resp.code===1000 ) {
                    this.$message.success('操作成功！');
                    this.lazyDialogVisible = false;
                }
            });
        },
        getStatusText(status) {
            if( this.type==1 ) return status==1? '成功': status==2? '失败': '待下发';
            if( this.type==2 ) return status==true? '成功': '失败';
        },
        lockTypeText(type) {
            var typeArray =  ['', '远程开锁', '超级密码', '机械开锁', '离线密码', '离线卡', '限时指纹', '限时密码', '限时感应', '限时人脸', '蓝牙开锁'];
            return typeArray[type] || '暂无详情';
        },
        faceImgChange($event) {
            var {remark, src, datetime} = $event;

            var formData = new FormData();
            function dataURItoBlob(dataURI) {//图片转成Buffer
                var byteString = atob(dataURI.split(',')[1]);
                var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
                var ab = new ArrayBuffer(byteString.length);
                var ia = new Uint8Array(ab);
                for (var i = 0; i < byteString.length; i++) {
                    ia[i] = byteString.charCodeAt(i);
                }
                return new Blob([ab], {type: mimeString});
            }
            var blob = dataURItoBlob(src);

            // const a= document.createElement("a")
            // a.href = URL.createObjectURL(blob)
            // a.download = "fileName" // 这里填保存成的文件名
            // a.click()
            // URL.revokeObjectURL(a.href);

            formData.append('lockId', this.data.lockId);
            formData.append('facesImage', blob);
            formData.append('startTime', datetime[0]);
            formData.append('endTime', datetime[1]);
            formData.append('remark', remark);

            var url = newService.Api.saveFaces + '/' + this.data.lockId
            newService.httpPost(url, formData, {
                bussinessNo: this.userInfo.userNo,
                'Content-Type': 'multipart/form-data'
            }).then(resp=>{
                if( resp.code===1000 ) {
                    this.$message.success('操作成功！');
                    this.faceDialogVisible = false;
                    this.currentChange(1);
                }
            });
        },
        fetchFaceList() {
            var url = newService.Api.getImgList + '/' + this.data.lockId;
            var params = {
                currentPage: this.pageIndex,
                pageSize: this.pageSize,
                name: this.nickName
            };
            newService.httpGet(url, params, {bussinessNo: this.userInfo.userNo}).then(resp=>{
                if( resp ){
                    var response = resp.data;
                    let {content, totalCount} = response;
                    this.tableData = content;
                    this.totalElements = totalCount;
                }
            });
        },
        fetchLog() {
            var url = newService.Api.getLogList + '/' + this.data.lockId;
            var params = {
                pageNum: this.pageIndex,
                pageSize: this.pageSize,
                openType: this.queryOpenType,
                startTime: this.expireTime ? this.expireTime[0]: '',
                endTime: this.expireTime ? this.expireTime[1]: ''
            };
            newService.httpGet(url, params, {bussinessNo: this.userInfo.userNo}).then(resp=>{
                if( resp ){
                    var response = resp.data;
                    let {content, totalCount} = response;
                    this.tableData = content;
                    this.totalElements = totalCount;
                }
            });
        },
        fetchRecordList(){
            var url = this.$obHttp.Api.getCardList, params = {
                clientId: this.data.clientId,
                pageIndex: this.pageIndex,
                pageSize: this.pageSize
            };
            this.$obHttp.httpGet(url, params).then(response=>{
                if( response ){
                    let {content, totalCount} = response.result;
                    this.tableData = content;
                    this.totalElements = totalCount;
                }
            });
        },
        currentChange(currentPage){
            this.pageIndex = currentPage;
            if( this.type == 1 ) this.fetchFaceList();
            else if( this.type == 2 ) this.fetchLog();
			else this.fetchRecordList();
        }
    }
}
</script>

<style lang="scss" scoped>
    .lz-opticalbox{
        margin-bottom: 40px;
    }
</style>

